package com.fc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fc.context.BaseContext;
import com.fc.dto.RouteDTO;
import com.fc.dto.pageQuery.RoutePageQueryDTO;
import com.fc.entity.Route;
import com.fc.exception.RouteException;
import com.fc.mapper.RouteMapper;
import com.fc.result.PageResult;
import com.fc.service.IRouteService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class RouteServiceImpl extends ServiceImpl<RouteMapper, Route> implements IRouteService {

    @Override
    public void savaRoute(RouteDTO routeDTO) {
        QueryWrapper<Route> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("region_id", routeDTO.getRegionId());
        List<Route> routeList = list(queryWrapper);
        long routeNumber = 1L;
        // 判断是否存在当前区域线路
        if (routeList != null && !routeList.isEmpty()) {
            // 存在，那就在当前区域的最大线路加1
            routeNumber = routeList.stream()
                    .mapToLong(Route::getRouteNumber)
                    .max()
                    .orElse(0) + 1;
        }
        if (routeDTO.getCoefficient().compareTo(BigDecimal.ZERO) < 0) {
            throw new RouteException("物流系数异常");
        }
        Route route = BeanUtil.copyProperties(routeDTO, Route.class);
        route.setRouteNumber(routeNumber);
        route.setCreateTime(LocalDateTime.now());
        route.setCreateUser(BaseContext.getCurrentId());
        route.setUpdateTime(LocalDateTime.now());
        route.setUpdateUser(BaseContext.getCurrentId());
        save(route);
    }

    @Override
    public void updateRoute(RouteDTO routeDTO) {
        Route route = BeanUtil.copyProperties(routeDTO, Route.class);
        route.setUpdateUser(BaseContext.getCurrentId());
        route.setUpdateTime(LocalDateTime.now());
        updateById(route);
    }

    @Override
    public PageResult listRoute(RoutePageQueryDTO routePageQueryDTO) {
        Page<Route> page = new Page<>(routePageQueryDTO.getPageNum(), routePageQueryDTO.getPageSize());
        Long regionId = routePageQueryDTO.getRegionId();
        Integer transportType = routePageQueryDTO.getTransportType();
        Page<Route> pageResult = lambdaQuery()
                .eq(regionId != null, Route::getRegionId, regionId)
                .eq(transportType != null, Route::getTransportType, transportType)
                .page(page);
        return new PageResult(pageResult.getTotal(), pageResult.getRecords());
    }
}
